package com.ruoyi.framework.web.service;

import com.ruoyi.common.core.domain.DTO.InsertUserAddressBO;
import com.ruoyi.common.core.domain.DTO.UpdateUserAddressBO;
import com.ruoyi.common.core.domain.entity.UserAddress;
import com.ruoyi.system.mapper.UserAddressMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.List;

@Slf4j
@Component
@Transactional
public class UserAddressService {
    @Autowired
    private UserAddressMapper userAddressMapper;

    public void insertUserAddress(InsertUserAddressBO insertUserAddressBO) {
        Long userId = insertUserAddressBO.getUserId();
        //查看是否设置默认地址
        if (insertUserAddressBO.getIsDefault() == 1) {
            //查看该用户是否已有默认地址
            UserAddress defaultAddress = userAddressMapper.selectDefaultByUserId(userId);
            if (!ObjectUtils.isEmpty(defaultAddress)) {
                resetDefaultByUserId(userId);
            }
        }
        UserAddress userAddress = new UserAddress();
        BeanUtils.copyProperties(insertUserAddressBO, userAddress);
        userAddressMapper.insertUserAddress(userAddress);
    }

    public void updateUserAddress(UpdateUserAddressBO updateUserAddressBO) {
        //查看是否设置默认地址
        if (!ObjectUtils.isEmpty(updateUserAddressBO.getIsDefault()) && updateUserAddressBO.getIsDefault() == 1) {
            //重置用户的默认地址
            resetDefaultByUserId(updateUserAddressBO.getUserId());
        }
        UserAddress userAddress = new UserAddress();
        BeanUtils.copyProperties(updateUserAddressBO, userAddress);
        userAddressMapper.updateUserAddress(userAddress);
    }

    //根据用户id查询地址列表
    public List<UserAddress> selectByUserId(Long userId) {
        return userAddressMapper.selectByUserId(userId);
    }

    //根据用户查询默认地址
    public UserAddress selectDefaultByUserId(Long userId) {
        return userAddressMapper.selectDefaultByUserId(userId);
    }

    void resetDefaultByUserId(Long userId) {
        userAddressMapper.resetDefaultByUserId(userId);
    }
}
